package API.ObjectAPI;

//作为clone示范的类Information，继承Cloneable接口以支持clone
class InformationTwo implements Cloneable{
    private int id;
    private String name;
    private String password;
    private int[] data;

    public InformationTwo() {
    }

    public InformationTwo(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public InformationTwo(int id, String name, String password, int[] data) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.data = data;
    }

    //将类中data数组属性转换为String类型返回
    private String transferData(){
        StringBuilder dataInfor = new StringBuilder();
        dataInfor.append("[");
        for (int i = 0; i < data.length; i++) {
            dataInfor.append(data[i]);
            if(i < data.length - 1) {
                dataInfor.append(",");
            }
        }
        dataInfor.append("]");
        return dataInfor.toString();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int[] getData() {
        return data;
    }

    public void setData(int index, int data) {
        this.data[index] = data;
    }

    public String toString() {
        return "{id = " + id + ", name = " + name + ", password = " + password + ", data = " + transferData() + "}";
    }

    @Override
    //重写clone方法以提供支持
    protected Object clone() throws CloneNotSupportedException {
        InformationTwo result = new InformationTwo(this.id, this.name, this.password);
        int[] newData = new int[this.data.length];
        System.arraycopy(this.data, 0, newData, 0, this.data.length);
        result.data = newData;
        return result;
    }

}

public class DeepClone {
    public static void main(String[] args) {
        InformationTwo information1 = new InformationTwo(1, "John", "Doe", new int[]{1, 2, 3});
        System.out.println(information1);
        try {
            InformationTwo information2 = (InformationTwo) information1.clone();
            System.out.println(information2);
            information1.setData(0, 10);
            System.out.println(information2);
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}
